package servlets;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.CandidateService;
import service.PositionService;
import service.UserService;
import entityJPA.Candidate;
import entityJPA.Candidatecomment;
import entityJPA.Position;
import entityJPA.User;

/**
 * Servlet implementation class displayCandidateServlet
 */
@WebServlet("/displayCandidateServlet")
public class DisplayCandidateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private CandidateService candidateService;

	@EJB
	private PositionService posService;

	@EJB
	private UserService usrService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DisplayCandidateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response) Method used for loading data before redirecting to
	 *      candidateDisplay.jsp
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<Candidate> list = candidateService.getCandidates();
		HttpSession h = request.getSession();
		//h.setAttribute("operationIsSuccesful", "no");

		try {
			String usertype = (String) request.getSession().getAttribute("savedUserType");
			User u=usrService.getUserByUserName((String) request.getSession().getAttribute("savedUserName"));
			if (usertype.equals("Director General")) {
				list = candidateService.getCandidates();
			} else {
				// get the candidates recommended for this user position	
				list = candidateService.getCandidatesForUser(u);
			}

			if (request.getParameter("next") != null) {
				
				h.setAttribute("index", (Integer) (h.getAttribute("index")) + 5);
				h.setAttribute("operationIsSuccesful", "no");
			}
			if (request.getParameter("previous") != null) {
				h.setAttribute("index", (Integer) (h.getAttribute("index")) - 5);
				h.setAttribute("operationIsSuccesful", "no");
			}

			// if the user tries to filter the results
			if (request.getParameter("searchCandidateButton") != null) {
				// filtering by first name
				if (request.getParameter("searchCandidate").equals("firstName")){

					list = candidateService.filterByFirstName(request
							.getParameter("NameSearch"));
					Iterator<Candidate> it=list.iterator();
 					while(it.hasNext()){
						if(it.next().getPosition().getIdUser()!=u.getIdUser())
							it.remove();
					}
 					h.setAttribute("operationIsSuccesful", "no");
				}
				// filtering by last name
				else {
					list = candidateService.filterByLastName(request.getParameter("NameSearch"));
					Iterator<Candidate> it=list.iterator();
					while(it.hasNext()){
						if(it.next().getPosition().getIdUser()!=u.getIdUser())
							it.remove();
					}
					h.setAttribute("operationIsSuccesful", "no");
				}
			}

			// setting up the list attribute
			h.setAttribute("list", list);
			if (h.getAttribute("index") == null || (Integer) h.getAttribute("index") >= list.size())
				h.setAttribute("index", 0);
			if (h.getAttribute("index") == null || (Integer) h.getAttribute("index") < 0)
				h.setAttribute("index", 0);

			// setting up positions

			List<Position> pos = null;

			pos = posService.getActivePositions();

			h.setAttribute("pos", pos);
			response.sendRedirect("candidateDisplay.jsp");
		} catch (Exception e) {
			h.setAttribute("exceptionMessage",
					"An error occured while trying to process your request. Please try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

}
